<template>
	<view class="payment">
		<u-loading-page :loading="is_paying" :loading-text="loading_word"></u-loading-page>
		<view class="time">
			支付倒计时：
			<u-count-down @finish="deleteOrder" :time="vuex_config.pay_countdown_sec * 1000"
				format="mm:ss"></u-count-down>
		</view>
		<view class="payment-message">
			<view class="payment-message-tit">
				支付信息
			</view>
			<view class="payment-message-con">
				<view class="payment-message-image-text">
					<image src="../../static/images/store.png" mode=""></image>
					<text>{{orderInfo.store_name}}-{{orderInfo.room_name}}</text>
				</view>

				<view class="payment-message-image-text">
					<image src="../../static/images/calender.png" mode=""></image>
					<text>{{moment(orderInfo.starttime).format('MM-DD HH:mm')}} - {{moment(orderInfo.endtime).format('HH:mm')}}</text>
				</view>
				<view class="payment-message-con-money">
					<image src="../../static/images/zd.png" mode=""></image>
					<text>{{orderInfo.price}}元</text>
				</view>
			</view>
		</view>
		<view class="payment-way">
			<view class="payment-way-tit">
				支付方式
			</view>
			<view class="payment-way-con">
				<view class="" :class="{activeType:0===activeIndex}" @click="btnDisabled(0)"></view>
				<text>余额支付 （{{vuex_user.balance}}元 充值有优惠）</text>
			</view>
			<view class="payment-way-con">
				<view class="" :class="{activeType:1===activeIndex}" @click="btnDisabled(1)"></view>
				<text>微信支付</text>
			</view>

		</view>
		<view class="payment-hint">
			<image src="/static/images/tips.png" mode=""></image>
			<text>预约开始前{{vuex_config.rent_refund}}小时可以在“我的订单”自助退订。</text>
		</view>
		<view class="payment-statement">
			<view class="agress-content" @click.stop="changeIsAgree">
				<view class="radio" :class="{radioActive:isAgree}">
					<u-icon color="#fff" v-show="isAgree" name="checkbox-mark"></u-icon>
				</view>
				<view class="read">
					本人已阅读并同意<text @click.stop="goAgree">《{{agreement_title}}》</text>
				</view>
			</view>
			<button open-type="getPhoneNumber" @getphonenumber="getphonenumber" v-if="!vuex_user.mobile" @click.stop>支付
				{{orderInfo.price}}元</button>
			<button v-else-if="is_transzaction_end" @click="toMyReservePage">跳转至我的预约</button>
			<button @click="goPay" v-else :disabled="is_paying">支付 {{orderInfo.price}}元</button>

		</view>
		<u-modal :show="show_alarm" @confirm="show_alarm=!show_alarm" title="温馨提示" :content="`请阅读和同意“${agreement_title}”`" confirmColor="#606266"></u-modal>
	</view>
</template>

<script>
	import moment from 'moment'
	import {
		post_order_info_api,
		get_user_phone_api,
		save_user_info_api,
		get_user_info,
		create_wechat_pay_api,
		check_wechat_pay_success_api,
		update_blance_api,
		balance_pay_api,
		update_reservation_pay_api,
		delete_reservation_api,
		get_agreement_api,
	} from '@/common/api.js'
	export default {
		data() {
			return {
				temp: 0,
				moment: moment,
				// 是否同意了霸王条款
				isAgree: uni.getStorageSync('isAgree') || true,
				// 总金额
				activeIndex: 1,
				radiolist: [{
						name: '',
						index: 0
					},
					{
						name: '微信支付',
						index: 1
					},
				],
				// 下单需要的数据
				payInfo: {
					type: 1,
					item_key: "",
				},
				orderInfo: {},

				loading_word: '',
				is_paying: false,
				is_transzaction_end: false,
				
				agreement_title: '协议',
				show_alarm: 0,
			};
		},
		onLoad() {
			// #ifdef MP-WEIXIN
			wx.enableAlertBeforeUnload({
				message: "返回后将删除此预约",
			});
			// #endif
			this.getInfo()
			get_agreement_api({
				id: 1
			}).then(res => {
				if (1 == res.code) {
					this.agreement_title = res.data.title
				}
			})
		},
		methods: {

			goPay() {
				if (!this.isAgree) {
					this.show_alarm = 1
					return 
				}

				// 余额支付
				if (this.payInfo.type == 2) {
					uni.showModal({
						title: '提示',
						content: `你确认要余额支付: ${this.orderInfo.price}吗？`,
						success: (res) => {
							if (res.confirm) {
								this.is_paying = true
								this.loading_word = '请求支付...'

								balance_pay_api({
									price: this.orderInfo.price
								}).then(res => {
									if (1 == res.code) { // 支付成功后更新预约
										this.loading_word = '更新预约状态...'
										return update_reservation_pay_api({
											reserve_id: this.orderInfo.reserve_id,
											pay_way: 2,
											item_id: res.data.balance_id
										})
									} else { // 支付失败
										return Promise.reject(res.msg)
									}
								}).then(res => {
									if (1 == res.code) { // 预约更新成功
										this.is_transzaction_end = true
										this.$u.toast(res.msg, 2000);
										this.updateUserInfo() // 同步服务端，更新本地用户数据
										setTimeout(() => {
											this.$u.route({
												url: '/pages/openDoor/openDoor',
												type: 'tab',
											})
										}, 2000)
									} else { // 预约更新失败
										return Promise.reject(res.msg)
									}
								}).catch(msg => {
									this.$u.toast(msg)
								}).finally(() => {
									this.is_paying = false
									this.$u.vuex('vuex_reserve_info', {}) // 避免在教室页删除
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				} else {
					//w微信支付
					uni.showModal({
						title: '提示',
						content: `你确认要微信支付: ${this.orderInfo.price}吗？`,
						success: (res) => {
							let data = null;
							if (res.confirm) {
								this.is_paying = true
								this.loading_word = '请求支付...'

								create_wechat_pay_api({
									type: 1, //预约
									item_key: this.orderInfo.reserve_id,
								}).then(res => {
									data = res.data
									if (0 == res.code) {
										this.$u.toast(res.msg)
										return
									}
									return new Promise((resolve, reject) => {
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: data.timeStamp,
											nonceStr: data.nonceStr,
											package: data.package,
											signType: data.signType,
											paySign: data.paySign,
											success: function(res) {
												resolve(res)
											},
											fail: function(err) {
												return     //不向下走了
											}
										});
									})
								}).then(res => {
									//检查是是否成功
									this.loading_word = `检查支付...`
									return check_wechat_pay_success_api({
										transaction_id: data.transaction_id
									})
								}).then(res => {
									if (1 == res.code) {
										this.loading_word = '更新预约状态...'
										return update_reservation_pay_api({
											reserve_id: this.orderInfo.reserve_id,
											pay_way: 3,
											item_id: data.transaction_id
										})
									} else if (2 == res.code) { // 订单未支付
										return Promise.reject(res.msg)
									} else { // 订单支付失败
										return Promise.reject(res.msg)
									}
								}).then(res => {
									if (1 == res.code) { // 预约更新成功
										this.is_transzaction_end = true
										this.$u.toast(res.msg, 2000);
										this.updateUserInfo() // 同步服务端，更新本地用户数据
										setTimeout(() => {
											this.$u.route({
												url: '/pages/openDoor/openDoor',
												type: 'tab',
											})
										}, 2000)
									} else { // 预约更新失败
										return Promise.reject(res.msg)
									}
								}).catch(msg => {
									this.$u.toast(msg)
								}).finally(() => {
									this.is_paying = false
									this.$u.vuex('vuex_reserve_info', {}) // 避免在教室页删除
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				}

			},

			getphonenumber(res) {
				if (res.detail.errMsg == 'getPhoneNumber:fail user deny') {} else if ("getPhoneNumber:ok" == res
					.detail
					.errMsg) {
					get_user_phone_api({
							encryptedData: res.detail.encryptedData,
							iv: res.detail.iv,
						})
						.then(res => {
							get_user_info().then(resg => {
								save_user_info_api({
										...resg.data,
										mobile: res.data.phone
									})
									.then(ress => {
										if (1 == ress.code) {
											this.$u.vuex('vuex_user', Object.assign(this.vuex_user,
												resg
												.data, ress.data))
											// this.goPay()
										} else {
											this.$u.toast(ress.msg);
										}
									})
							})
						})
				}
			},
			getInfo() {
				post_order_info_api(this.vuex_reserve_info).then(res => {
					console.log(res);
					this.orderInfo = res.data
					this.$u.vuex('vuex_reserve_info', res.data) // 改变了本地vuex_reserve_info的值，如果用户返回到上一页，将删除此创建的订单
				})
			},
			changeIsAgree() {
				this.isAgree = !this.isAgree
			},
			// 支付方式
			btnDisabled(index) {
				if (this.vuex_user.balance < this.orderInfo.price) return this.$u.toast('当前余额小于支付金额')
				if (index === 0) {
					this.payInfo.type = 2;
				} else {
					this.payInfo.type = 1;
				}
				this.activeIndex = index
			},
			deleteOrder() {
				delete_reservation_api({
					id: this.orderInfo.reserve_id
				}).then((res) => {
					this.$u.vuex('vuex_reserve_info', {})
					this.$u.toast('待支付时间结束，请重新预约', 3000)
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}, 3000)
				})
			},
			toMyReservePage() {
				this.$u.route({
					url: '/pages/openDoor/openDoor',
					type: 'tab',
				})
			},
			goAgree() {
				uni.navigateTo({
					url: `/pages/paymentPage/agreement`
				})
			},
		}
	};
</script>

<style lang="scss">
	/deep/.u-count-down__text {
		color: #fff !important;
	}

	.payment {
		.time {
			height: 66rpx;
			background: #40C6A1;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 24rpx;
			font-size: 28rpx;
			color: #fff;
		}

		box-sizing: border-box;
		padding: 0 24rpx;
		margin-top: 32rpx;

		.payment-message {
			width: 702rpx;
			height: 392rpx;
			box-sizing: border-box;
			padding: 0 24rpx;

			background: #F3F4F6;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			overflow: hidden;
			margin-bottom: 32rpx;

			.payment-message-tit {
				margin-top: 24rpx;
				padding-bottom: 24rpx;
				border-bottom: 2rpx solid #C0C4CC;
				font-size: 36rpx;
			}
		}

		.payment-message-con {
			margin-top: 24rpx;

			.payment-message-con-money {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				text {
					font-size: 36rpx;
					font-weight: 500;
					color: #000000;
				}

				image {
					flex-shrink: 0;
					width: 64rpx;
					height: 64rpx;
					margin-right: 24rpx;
				}
			}

			.payment-message-image-text {
				display: flex;
				align-items: center;
				margin-bottom: 26rpx;

				image {
					flex-shrink: 0;
					width: 64rpx;
					height: 64rpx;
					margin-right: 24rpx;
				}

				text {
					font-size: 32rpx;
					font-weight: 500;
					color: #606266;
				}

			}
		}

		.payment-way {
			width: 702rpx;
			height: 290rpx;
			box-sizing: border-box;
			padding: 0 24rpx;

			background: #F3F4F6;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			overflow: hidden;
			margin-bottom: 32rpx;

			.payment-way-tit {
				margin-top: 24rpx;
				padding-bottom: 24rpx;
				border-bottom: 2rpx solid #C0C4CC;
				font-size: 36rpx;
			}

			.payment-way-con {
				display: flex;
				margin-top: 34rpx;

				.activeType {
					background-color: #40C6A1;
				}

				view {
					width: 36rpx;
					height: 36rpx;

					border-radius: 50%;
					margin-right: 24rpx;
					border: 4rpx solid gray;
				}

				text {
					font-size: 32rpx;
					color: #000000;
					font-weight: 500;
				}


				.active {
					background: #40C6A1;
				}
			}
		}

		.payment-hint {
			display: flex;
			align-items: center;

			image {
				width: 36rpx;
				height: 36rpx;
			}

			text {
				font-size: 28rpx;
				font-weight: 500;
				color: #C0C4CC;
				margin-left: 26rpx;
			}
		}

		.payment-statement {
			position: fixed;
			bottom: 38rpx;
			left: 0;
			right: 0;

			.agress-content {
				width: 87%;
				margin: 0 auto;
				display: flex;
				margin-bottom: 40rpx;

				.radio {
					margin-right: 16rpx;
					width: 36rpx;
					height: 36rpx;
					border-radius: 4rpx 4rpx 4rpx 4rpx;
					border: 2rpx solid #909399;
				}

				.read {
					font-size: 28rpx;
					font-weight: 400;
					color: #606266;
				}

				.radioActive {
					background-color: #40C6A1;
				}
			}

			.uni-list {
				margin-left: 48rpx;
				margin-bottom: 48rpx;

				.checkbox-3 {
					font-size: 28rpx;
					font-weight: 400;
					color: #606266;
				}
			}

			button {
				width: 654rpx;
				height: 96rpx;
				color: #F3F4F6;
				background: #40C6A1;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
			}
		}
	}

	:deep .u-icon__icon {
		color: red !important;
	}
</style>